import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { View, Text, Image, ScrollView } from '@tarojs/components';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { debounce } from '@/utils/helper';
import utils from '@/utils/index';
import Imagelocation from '@/components/Imagelocation';
import pStar from '@/images/taihuHomePage/star.png';
import pTuancanbiaoqian from '@/images/common/tuancanbiaoqian.png';
import pNotice from '@/images/common/notice.png';
import './index.scss';

const CouponShopListPage = ({ dispatch, couponShopList = [], couponShopFinished = false }) => {
  const { router } = getCurrentInstance();
  const { params: { configId, couponId, sourceType } = {} } = router;

  const [curLocation, setCurLocation] = useState(null);

  const showNextPage = debounce(() => {
    !couponShopFinished && getcouponShopList();
  }, 200);

  useEffect(() => {
    getLocation();
  }, []);

  useEffect(() => {
    curLocation && getcouponShopList();
  }, [curLocation]);

  const getcouponShopList = () => {
    const { latitude, longitude } = curLocation;
    dispatch({
      type: 'giftCard/getCouponShopListModel',
      payload: {
        configId,
        couponId,
        sourceType,
        pageSize: 20,
        lat: latitude,
        lon: longitude,
      },
    });
  };

  const getLocation = async () => {
    let localLocation = utils.getLocalEffectLocation();
    if (localLocation) {
      const { latitude, longitude } = localLocation;
      setCurLocation({ latitude, longitude });
    } else {
      Taro.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        timeout: 5000,
        success: (res) => {
          const { latitude, longitude } = res;
          const timeStamp = new Date().getTime();
          setCurLocation({ latitude, longitude });
          utils.setLocalStorage('location', { latitude, longitude, timeStamp });
        },
        fail: () => {
          setCurLocation({ latitude: undefined, longitude: undefined });
        },
      });
    }
  };

  return (
    <View className="coupon_storeList">
      <ScrollView
        className="contentPage"
        scrollY
        lowerThreshold={340}
        onScrollToLower={showNextPage}
      >
        <LocalOrg dataList={couponShopList} />

        {couponShopFinished && couponShopList.length > 8 && (
          <View className="end">- 我是有底线的 -</View>
        )}
        {couponShopFinished && couponShopList.length == 0 && (
          <View className="noShop">暂无商户，敬请期待</View>
        )}
      </ScrollView>
    </View>
  );
};

const LocalOrg = ({ dataList = [] }) => {
  const goShopDetail = (shopId, merchantId) => {
    Taro.navigateTo({
      url: '/mainSubPack/takeOutShop/index' + '?' + 'orgId=' + shopId + '&merchantId=' + merchantId,
    });
  };
  console.log('dataList', dataList);
  return (
    <View className="storeList">
      {dataList.length > 0 &&
        dataList.map((shop) => (
          <View
            className="shop localOrg"
            key={'slocalOrgShop' + shop.id}
            onClick={() => goShopDetail(shop.id, shop.merchantId)}
          >
            {shop.activityList &&
              shop.activityList.length > 0 &&
              shop.activityList.map((activity, idx) => {
                let src = '';
                if (activity.type == 1) {
                  //团餐
                  src = pTuancanbiaoqian;
                }
                if (activity.isShow == 1) {
                  return <Image className="tcIcon" src={src} key={'slocalOrgActivity' + idx} />;
                } else {
                  return null;
                }
              })}
            <View className="left">
              <Imagelocation className="shopIcon" src={shop.logo} type="shop" />
            </View>
            <View className="right">
              <View className="name">{shop.name}</View>
              <View className="info">
                <View className="infoLeft">
                  <Image
                    className="starIcon"
                    src={typeof shop.grade !== 'undefined' ? pStar : ''}
                  />
                  <Text className="starNum">{shop.grade || ''}</Text>
                </View>
                <View className="infoRight">
                  <Text className="distance">
                    {typeof shop.distance !== 'undefined' ? shop.distance + 'km' : ''}
                  </Text>
                </View>
              </View>
              <View className="industry">{shop.secondIndustryName || ''}</View>
              <View className="notice">
                {shop.notice && shop.notice.length > 0 && (
                  <>
                    <Text>店铺</Text>
                    <Image className="noticeIcon" src={pNotice} />
                    <Text>：{shop.notice}</Text>
                  </>
                )}
              </View>
              {shop.policy && shop.policy.length > 0 && (
                <View className="manjianLine">
                  {shop.policy.map((item, index) => (
                    <Text className="manjian" key={'slocalOrgManjian' + index}>
                      {item}
                    </Text>
                  ))}
                </View>
              )}
            </View>
          </View>
        ))}
    </View>
  );
};

export default connect(({ giftCard }) => ({
  couponShopList: giftCard.couponShopList,
  couponShopFinished: giftCard.couponShopFinished,
}))(CouponShopListPage);
